package controller

import (
	"net/http"
	"strconv"

	"gitee.com/ysl729895/go-mall/internal/model"
	"gitee.com/ysl729895/go-mall/internal/service"
	"github.com/gin-gonic/gin"
)

// PermissionController 权限管理控制器，处理权限相关的 HTTP 请求
// 包括权限的增删改查

type PermissionController struct {
	service service.PermissionService
}

// NewPermissionController 构造函数，注入 PermissionService
func NewPermissionController(service service.PermissionService) *PermissionController {
	return &PermissionController{service: service}
}

// CreatePermission 创建新权限
// @Summary 创建权限
// @Tags 权限管理
// @Accept json
// @Produce json
// @Param permission body model.Permission true "权限信息"
// @Success 201 {object} model.Permission
// @Router /api/permissions [post]
func (c *PermissionController) CreatePermission(ctx *gin.Context) {
	var req struct {
		Name        string `json:"name" binding:"required"`
		Description string `json:"description"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, model.ErrorResponse{
			Code:    http.StatusBadRequest,
			Message: "请求参数格式不正确",
			Error:   err.Error(),
		})
		return
	}
	permission := &model.Permission{Name: req.Name, Description: req.Description}
	if err := c.service.CreatePermission(req.Name, req.Description); err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, model.ErrorResponse{
			Code:    http.StatusInternalServerError,
			Message: "创建权限失败",
			Error:   err.Error(),
		})
		return
	}
	ctx.Set("responseData", permission)
	ctx.Set("responseMessage", "创建权限成功")
	ctx.Status(http.StatusCreated)
}

// UpdatePermission 通过 POST /update 实现权限更新
// @Summary 更新权限
// @Tags 权限管理
// @Accept json
// @Produce json
// @Param permission body model.Permission true "权限信息"
// @Success 200 {object} model.Permission
// @Failure 400 {object} model.ErrorResponse
// @Failure 500 {object} model.ErrorResponse
// @Router /api/permissions/update [post]
func (c *PermissionController) UpdatePermission(ctx *gin.Context) {
	var req struct {
		ID          uint   `json:"id" binding:"required"`
		Name        string `json:"name" binding:"required"`
		Description string `json:"description"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, model.ErrorResponse{
			Code:    http.StatusBadRequest,
			Message: "请求参数格式不正确",
			Error:   err.Error(),
		})
		return
	}
	if err := c.service.UpdatePermission(req.ID, req.Name, req.Description); err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, model.ErrorResponse{
			Code:    http.StatusInternalServerError,
			Message: "更新权限失败",
			Error:   err.Error(),
		})
		return
	}
	ctx.Set("responseData", gin.H{"id": req.ID, "name": req.Name, "description": req.Description})
	ctx.Set("responseMessage", "更新权限成功")
}

// DeletePermission 通过 POST /delete 实现权限删除
// @Summary 删除权限
// @Tags 权限管理
// @Accept json
// @Produce json
// @Param id body model.Permission true "权限ID"
// @Success 200 {string} string "删除成功"
// @Failure 400 {object} model.ErrorResponse
// @Failure 500 {object} model.ErrorResponse
// @Router /api/permissions/delete [post]
func (c *PermissionController) DeletePermission(ctx *gin.Context) {
	var req struct {
		ID uint `json:"id" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, model.ErrorResponse{
			Code:    http.StatusBadRequest,
			Message: "请求参数格式不正确",
			Error:   err.Error(),
		})
		return
	}
	if err := c.service.DeletePermission(req.ID); err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, model.ErrorResponse{
			Code:    http.StatusInternalServerError,
			Message: "删除权限失败",
			Error:   err.Error(),
		})
		return
	}
	ctx.Set("responseData", gin.H{"id": req.ID})
	ctx.Set("responseMessage", "删除权限成功")
}

// GetPermission 查询权限（支持通过 ?id= 查询单个，否则查全部）
// @Summary 查询权限
// @Tags 权限管理
// @Param id query int false "权限ID"
// @Success 200 {object} model.Permission
// @Success 200 {array} model.Permission
// @Router /api/permissions [get]
func (c *PermissionController) GetPermission(ctx *gin.Context) {
	idStr := ctx.Query("id")
	if idStr == "" {
		permissions, err := c.service.GetAllPermissions()
		if err != nil {
			ctx.AbortWithStatusJSON(http.StatusInternalServerError, model.ErrorResponse{
				Code:    http.StatusInternalServerError,
				Message: "查询权限列表失败",
				Error:   err.Error(),
			})
			return
		}
		ctx.Set("responseData", permissions)
		return
	}
	id, err := strconv.Atoi(idStr)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, model.ErrorResponse{
			Code:    http.StatusBadRequest,
			Message: "无效的权限ID",
			Error:   err.Error(),
		})
		return
	}
	permission, err := c.service.GetPermissionByID(uint(id))
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusNotFound, model.ErrorResponse{
			Code:    http.StatusNotFound,
			Message: "权限未找到",
			Error:   err.Error(),
		})
		return
	}
	ctx.Set("responseData", permission)
}
